<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="物料编码" prop="materialCode">
        <el-input v-model="queryParams.materialCode" placeholder="请输入物料编码" clearable/>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-input v-model="queryParams.materialName" placeholder="请输入物料名称" clearable/>
      </el-form-item>
      <el-form-item label="物料型号" prop="materialSpecification">
        <el-input v-model="queryParams.materialSpecification" placeholder="请输入物料型号" clearable/>
      </el-form-item>
      <el-form-item label="物料类型">
        <el-cascader
          style="width: 500px"
          v-model="selectedType"
          :options="typeOptions"
          :props="{
          value:'value',
          label:'label',
          children:'children',
          checkStrictly:true
        }"
          @change="handleChange"
          clearable
          @keyup.enter.native="handleQuery"></el-cascader>
      </el-form-item>

      <el-form-item label="物料分类">
        <el-cascader
          style="width: 500px"
          v-model="selectedCategory"
          :options="categoryOptions"
          :props="{
          value:'value',
          label:'label',
          children:'children',
          checkStrictly:true
        }"
          @change="handleChange"
          clearable
          @keyup.enter.native="handleQuery"></el-cascader>
      </el-form-item>


      <el-form-item label="物料状态" prop="status">
        <el-select placeholder="请选择物料状态" v-model="queryParams.status">
          <el-option label="全部" value=""/>
          <el-option label="启用" value="1"/>
          <el-option label="停用" value="0"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['storage:material:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['storage:material:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['storage:material:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['storage:material:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="materialList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="物料编码" prop="materialCode" align="center"/>
      <el-table-column label="物料名称" prop="materialName" align="center"/>
      <el-table-column label="规格型号" prop="materialSpecification" align="center"/>
      <el-table-column label="物料类型名称" prop="erpMaterialType.name" align="center"/>
      <el-table-column label="物料分类名称" prop="erpMaterialCategory.name" align="center"/>
      <el-table-column label="物料状态" prop="status" align="center" :formatter="formatMaterialStatus"/>
      <el-table-column label="详细数据" align="center" type="expand" width="80px">
        <template #default="props">
          <el-descriptions style="padding:0 100px">
            <el-descriptions-item label="备注">{{ props.row.remark }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="padding:0 100px">
            <el-descriptions-item label="创建时间">{{ props.row.createdAt }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ props.row.updatedAt }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="padding:0 100px">
            <el-descriptions-item label="单位">{{ props.row.unit }}</el-descriptions-item>
          </el-descriptions>
          <el-descriptions style="padding:0 100px">
            <el-descriptions-item label="最大库存">{{ props.row.maxStock }}</el-descriptions-item>
            <el-descriptions-item label="安全库存">{{ props.row.safeStock }}</el-descriptions-item>
            <el-descriptions-item label="最小库存">{{ props.row.minStock }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['storage:material:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['storage:material:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料信息管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="物料编码" prop="materialCode">
          <el-input v-model="form.materialCode" placeholder="请输入物料编码"/>
        </el-form-item>

        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="form.materialName" placeholder="请输入物料名称"/>
        </el-form-item>
        <el-form-item label="规格型号" prop="materialSpecification">
          <el-input v-model="form.materialSpecification" placeholder="请输入规格型号"/>
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="form.unit" placeholder="请输入单位"/>
        </el-form-item>
        <el-form-item label="物料类型" prop="typeId">
          <el-cascader
            style="width: 500px"
            v-model="form.typeId"
            :options="typeOptions"
            :props="{
                    value:'value',
                    label:'label',
                    children:'children',
                    checkStrictly:true
                  }"
            @change="handleCascaderChange1"
            >
          </el-cascader>
        </el-form-item>
        <el-form-item label="物料分类" prop="categoryId">
          <el-cascader
            style="width: 500px"
            v-model="form.categoryId"
            :options="categoryOptions"
            :props="{
          value:'value',
          label:'label',
          children:'children',
          checkStrictly:true
        }"
            @change="handleCascaderChange2"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="最大库存" prop="maxStock">
          <el-input-number v-model="form.maxStock"/>
        </el-form-item>
        <el-form-item label="最小库存" prop="minStock">
          <el-input-number v-model="form.minStock"/>
        </el-form-item>
        <el-form-item label="安全库存" prop="safeStock">
          <el-input-number v-model="form.safeStock"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addMaterial, delMaterial, getMaterial, listMaterial, updateMaterial} from "@/api/storage/material"
import {getCategoryOptions} from "@/api/storage/materialClassification";
import {getTypeOptions} from "@/api/storage/materialType";


export default {
  name: "Material",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料信息管理表格数据
      materialList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 存储选择的类型信息
      selectedType: [],
      // 存储可选的类型信息
      typeOptions: [],
      // 存储选择的分类信息
      selectedCategory: [],
      // 存储可选的分类信息
      categoryOptions: [],
    }
  },
  created() {
    this.getList()
    this.loadTypeOptions()
    this.loadCategoryOptions()
  },
  methods: {
    // 加载分类级联选择器的数据
    loadCategoryOptions() {
      try {
        this.loading = true
        getCategoryOptions().then(response => {
          this.categoryOptions = response.data
        })
        this.loading = false
      } catch (error) {
        this.$message.error("加载分类数据失败")
      }
    },
    // 加载类型级联选择器的数据
    loadTypeOptions() {
      try {
        this.loading = true
        getTypeOptions().then(response => {
          this.typeOptions = response.data
        })
        this.loading = false
      } catch (error) {
        this.$message.error("加载类型数据失败")
      }
    },

    // 获取最后一级id
    handleChange() {
      //获取物料类型的最后一级id
      this.queryParams.typeId = this.selectedType[this.selectedType.length - 1]
      // 获取物料分类的最后一级id
      this.queryParams.categoryId = this.selectedCategory[this.selectedCategory.length - 1]

    },
    //获得修改界面中的物料类型的最后一级id
    handleCascaderChange1(value) {
      this.form.typeId = value[value.length - 1];
    },
    //获得修改界面中的物料分类的最后一级id
    handleCascaderChange2(value) {
      this.form.categoryId = value[value.length - 1];
    },
    // 格式化物料类型显示
    formatMaterialStatus(row) {
      const statusMap = {
        0: '停用',
        1: '启用',
      };
      return statusMap[row.status] || row.status;
    },
    /** 查询物料信息管理列表 */
    getList() {
      this.loading = true
      listMaterial(this.queryParams).then(response => {
        this.materialList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        materialCode: null,
        materialName: null,
        materialSpecification: null,
        unit: null,
        typeId: null,
        categoryId: null,
        minStock: null,
        maxStock: null,
        safeStock: null,
        status: null,
        remark: null,
        createdAt: null,
        updatedAt: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加物料信息管理"
      this.loadCategoryOptions()
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      this.loadCategoryOptions()
      getMaterial(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改物料信息管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateMaterial(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addMaterial(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除物料信息管理编号为"' + ids + '"的数据项？').then(function () {
        return delMaterial(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('storage/material/export', {
        ...this.queryParams
      }, `material_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
